package com.wujie.mall.domain.order;

import lombok.Data;
import lombok.Builder;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

import java.math.BigDecimal;

/**
 * 订单项实体
 * 
 * @author wujie
 * @since 2024-08-26
 */
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class OrderItem {

    /**
     * 订单项ID
     */
    private Long id;

    /**
     * 订单ID
     */
    private Long orderId;

    /**
     * 商品ID
     */
    private Long productId;

    /**
     * SKU ID
     */
    private Long skuId;

    /**
     * 商品名称
     */
    private String productName;

    /**
     * SKU名称
     */
    private String skuName;

    /**
     * 商品图片URL
     */
    private String productImage;

    /**
     * 单价
     */
    private BigDecimal unitPrice;

    /**
     * 数量
     */
    private Integer quantity;

    /**
     * 小计（单价 * 数量）
     */
    private BigDecimal totalPrice;

    /**
     * 商品属性（如：颜色:红色,尺寸:M）
     */
    private String attributes;

    /**
     * 计算小计
     */
    public void calculateTotalPrice() {
        if (unitPrice != null && quantity != null) {
            totalPrice = unitPrice.multiply(BigDecimal.valueOf(quantity));
        } else {
            totalPrice = BigDecimal.ZERO;
        }
    }

    /**
     * 验证订单项
     * @throws IllegalStateException 订单项信息不完整时抛出
     */
    public void validate() {
        if (productId == null) {
            throw new IllegalStateException("商品ID不能为空");
        }
        
        if (skuId == null) {
            throw new IllegalStateException("SKU ID不能为空");
        }
        
        if (productName == null || productName.trim().isEmpty()) {
            throw new IllegalStateException("商品名称不能为空");
        }
        
        if (unitPrice == null || unitPrice.compareTo(BigDecimal.ZERO) <= 0) {
            throw new IllegalStateException("商品单价必须大于0");
        }
        
        if (quantity == null || quantity <= 0) {
            throw new IllegalStateException("商品数量必须大于0");
        }
        
        // 重新计算小计并验证
        calculateTotalPrice();
        if (totalPrice == null || totalPrice.compareTo(BigDecimal.ZERO) <= 0) {
            throw new IllegalStateException("订单项小计必须大于0");
        }
    }

    /**
     * 获取格式化的属性字符串
     * @return 格式化的属性字符串
     */
    public String getFormattedAttributes() {
        if (attributes == null || attributes.trim().isEmpty()) {
            return "";
        }
        
        // 将 "颜色:红色,尺寸:M" 格式化为 "颜色：红色；尺寸：M"
        return attributes.replace(":", "：").replace(",", "；");
    }

    /**
     * 设置商品属性
     * @param key 属性名
     * @param value 属性值
     */
    public void addAttribute(String key, String value) {
        if (attributes == null) {
            attributes = key + ":" + value;
        } else {
            attributes += "," + key + ":" + value;
        }
    }
}